using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using UnityEngine;

namespace Framework.UI
{
    public abstract class UIFrame : IFrame
    {
        protected ScriptBinder scriptBinder;
        YooAsset.AssetHandle handle;
        public bool disposed { get; private set; } = false;
        public int Id { get; set; }

        protected virtual string ActivedScene { get; } = string.Empty;

        protected abstract void RegisterUIEvent();
        protected abstract void UnregisterUIEvent();
        protected abstract void InitScriptBinder();

        protected void PreFrameOpen()
        {
            UnityEngine.SceneManagement.SceneManager.activeSceneChanged += this.OnActivedSceneChanged;
        }

        void OnActivedSceneChanged(UnityEngine.SceneManagement.Scene pre, UnityEngine.SceneManagement.Scene current)
        {
            if(!string.IsNullOrEmpty(ActivedScene) && current.name != ActivedScene)
            {
                UIFrameManager.Instance.CloseFrame(this);
            }
        }

        protected void AftFrameClose()
        {
            UnityEngine.SceneManagement.SceneManager.activeSceneChanged -= this.OnActivedSceneChanged;
        }

        protected virtual void OnFrameOpen()
        {

        }

        protected virtual void OnFrameClose()
        {

        }

        protected virtual void OnShow()
        {

        }

        protected virtual void OnHide()
        {

        }

        private void OnEnable()
        {
            OnShow();
        }

        private void OnDisable()
        {
            OnHide();
        }

        public void OnDestroy()
        {
            if (disposed)
                return;
            disposed = true;
            OnFrameClose();
            AftFrameClose();
            UnregisterUIEvent();
            scriptBinder.DestroyWithFrame();
            Object.Destroy(scriptBinder.gameObject);
            handle?.Dispose();
            handle = null;
        }

        public void OnCreate(GameObject gameObject, YooAsset.AssetHandle handle)
        {
            this.handle = handle;
            scriptBinder = gameObject.GetComponent<ScriptBinder>();
            scriptBinder.ResetValue();
            scriptBinder.Setup(this.OnEnable,this.OnDisable,this.OnDestroy);

            InitScriptBinder();
            RegisterUIEvent();
            PreFrameOpen();
            OnFrameOpen();

            this.OnEnable();
        }
    }
}
